/**
 * 注册页面JavaScript逻辑
 */

// API基础地址
const API_BASE_URL = 'http://localhost:8080';

// DOM元素
const registerForm = document.getElementById('registerForm');
const accountInput = document.getElementById('account');
const passwordInput = document.getElementById('password');
const confirmPasswordInput = document.getElementById('confirmPassword');
const nameInput = document.getElementById('name');
const idNumInput = document.getElementById('idNum');
const ageInput = document.getElementById('age');
const emailInput = document.getElementById('email');
const registerBtn = document.getElementById('registerBtn');
const togglePasswordBtn = document.getElementById('togglePassword');
const toggleConfirmPasswordBtn = document.getElementById('toggleConfirmPassword');
const alertBox = document.getElementById('alertBox');
const alertMessage = document.getElementById('alertMessage');
const strengthFill = document.getElementById('strengthFill');
const strengthText = document.getElementById('strengthText');

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    bindEvents();
});

/**
 * 绑定事件
 */
function bindEvents() {
    registerForm.addEventListener('submit', handleRegister);
    togglePasswordBtn.addEventListener('click', () => togglePasswordVisibility('password'));
    toggleConfirmPasswordBtn.addEventListener('click', () => togglePasswordVisibility('confirmPassword'));
    passwordInput.addEventListener('input', checkPasswordStrength);

    accountInput.addEventListener('blur', validateAccount);
    passwordInput.addEventListener('blur', validatePassword);
    confirmPasswordInput.addEventListener('blur', validateConfirmPassword);
    nameInput.addEventListener('blur', validateName);
    idNumInput.addEventListener('blur', validateIdNum);
    ageInput.addEventListener('blur', validateAge);
    emailInput.addEventListener('blur', validateEmail);

    idNumInput.addEventListener('input', autoFillAgeFromIdNum);

    accountInput.addEventListener('input', () => clearError('accountError'));
    passwordInput.addEventListener('input', () => clearError('passwordError'));
    confirmPasswordInput.addEventListener('input', () => clearError('confirmPasswordError'));
    nameInput.addEventListener('input', () => clearError('nameError'));
    idNumInput.addEventListener('input', () => clearError('idNumError'));
    ageInput.addEventListener('input', () => clearError('ageError'));
    emailInput.addEventListener('input', () => clearError('emailError'));
}

/**
 * 处理注册
 */
async function handleRegister(event) {
    event.preventDefault();

    if (!validateForm()) {
        return;
    }

    const formData = {
        account: accountInput.value.trim(),
        password: passwordInput.value.trim(),
        name: nameInput.value.trim(),
        idNum: idNumInput.value.trim(),
        age: parseInt(ageInput.value),
        email: emailInput.value.trim() || null
    };

    setLoadingState(true);

    try {
        const response = await fetch(`${API_BASE_URL}/user/register`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });

        const result = await response.json();

        if (result.code === 200) {
            showAlert('注册成功！3秒后自动跳转到登录页面...', 'success');
            setTimeout(() => {
                window.location.href = 'login.html';
            }, 3000);
        } else {
            showAlert(result.errorMsg || '注册失败，请检查输入信息', 'error');
            setLoadingState(false);
        }
    } catch (error) {
        console.error('注册请求失败:', error);
        showAlert('网络错误，请检查服务器是否启动', 'error');
        setLoadingState(false);
    }
}

/**
 * 验证表单
 */
function validateForm() {
    let isValid = true;

    if (!validateAccount()) isValid = false;
    if (!validatePassword()) isValid = false;
    if (!validateConfirmPassword()) isValid = false;
    if (!validateName()) isValid = false;
    if (!validateIdNum()) isValid = false;
    if (!validateAge()) isValid = false;
    if (emailInput.value.trim() && !validateEmail()) isValid = false;

    return isValid;
}

/**
 * 验证账号
 */
function validateAccount() {
    const account = accountInput.value.trim();

    if (!account) {
        showError('accountError', '账号不能为空');
        accountInput.classList.add('error');
        return false;
    }

    if (account.length < 3 || account.length > 20) {
        showError('accountError', '账号长度应为3-20个字符');
        accountInput.classList.add('error');
        return false;
    }

    const accountRegex = /^[a-zA-Z0-9_]+$/;
    if (!accountRegex.test(account)) {
        showError('accountError', '账号只能包含字母、数字和下划线');
        accountInput.classList.add('error');
        return false;
    }

    clearError('accountError');
    accountInput.classList.remove('error');
    return true;
}

/**
 * 验证密码
 */
function validatePassword() {
    const password = passwordInput.value.trim();

    if (!password) {
        showError('passwordError', '密码不能为空');
        passwordInput.classList.add('error');
        return false;
    }

    if (password.length < 6) {
        showError('passwordError', '密码长度不能少于6个字符');
        passwordInput.classList.add('error');
        return false;
    }

    clearError('passwordError');
    passwordInput.classList.remove('error');
    return true;
}

/**
 * 验证确认密码
 */
function validateConfirmPassword() {
    const password = passwordInput.value.trim();
    const confirmPassword = confirmPasswordInput.value.trim();

    if (!confirmPassword) {
        showError('confirmPasswordError', '请再次输入密码');
        confirmPasswordInput.classList.add('error');
        return false;
    }

    if (password !== confirmPassword) {
        showError('confirmPasswordError', '两次输入的密码不一致');
        confirmPasswordInput.classList.add('error');
        return false;
    }

    clearError('confirmPasswordError');
    confirmPasswordInput.classList.remove('error');
    return true;
}

/**
 * 验证姓名
 */
function validateName() {
    const name = nameInput.value.trim();

    if (!name) {
        showError('nameError', '姓名不能为空');
        nameInput.classList.add('error');
        return false;
    }

    const nameRegex = /^[\u4e00-\u9fa5a-zA-Z]+$/;
    if (!nameRegex.test(name)) {
        showError('nameError', '姓名只能包含中文或字母');
        nameInput.classList.add('error');
        return false;
    }

    clearError('nameError');
    nameInput.classList.remove('error');
    return true;
}

/**
 * 验证身份证号
 */
function validateIdNum() {
    const idNum = idNumInput.value.trim();

    if (!idNum) {
        showError('idNumError', '身份证号不能为空');
        idNumInput.classList.add('error');
        return false;
    }

    const idNumRegex = /^\d{18}$/;
    if (!idNumRegex.test(idNum)) {
        showError('idNumError', '请输入正确的18位身份证号');
        idNumInput.classList.add('error');
        return false;
    }

    clearError('idNumError');
    idNumInput.classList.remove('error');
    return true;
}

/**
 * 验证年龄
 */
function validateAge() {
    const age = parseInt(ageInput.value);

    if (!age || isNaN(age)) {
        showError('ageError', '年龄不能为空');
        ageInput.classList.add('error');
        return false;
    }

    if (age < 0 || age > 150) {
        showError('ageError', '请输入有效的年龄（0-150）');
        ageInput.classList.add('error');
        return false;
    }

    clearError('ageError');
    ageInput.classList.remove('error');
    return true;
}

/**
 * 验证邮箱
 */
function validateEmail() {
    const email = emailInput.value.trim();

    if (!email) {
        clearError('emailError');
        emailInput.classList.remove('error');
        return true;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        showError('emailError', '请输入正确的邮箱格式');
        emailInput.classList.add('error');
        return false;
    }

    clearError('emailError');
    emailInput.classList.remove('error');
    return true;
}



/**
 * 检查密码强度
 */
function checkPasswordStrength() {
    const password = passwordInput.value;
    let strength = 0;

    if (password.length === 0) {
        strengthFill.className = 'strength-fill';
        strengthText.textContent = '';
        return;
    }

    if (password.length >= 6) strength++;
    if (password.length >= 10) strength++;
    if (/\d/.test(password)) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[^a-zA-Z0-9]/.test(password)) strength++;

    if (strength <= 2) {
        strengthFill.className = 'strength-fill weak';
        strengthText.textContent = '弱';
        strengthText.style.color = '#ff4757';
    } else if (strength <= 4) {
        strengthFill.className = 'strength-fill medium';
        strengthText.textContent = '中';
        strengthText.style.color = '#ffa502';
    } else {
        strengthFill.className = 'strength-fill strong';
        strengthText.textContent = '强';
        strengthText.style.color = '#26de81';
    }
}

/**
 * 从身份证号自动填充年龄
 */
function autoFillAgeFromIdNum() {
    const idNum = idNumInput.value.trim();

    // 仅当是18位数字时尝试提取年份
    if (/^\d{18}$/.test(idNum)) {
        try {
            // 尝试按标准身份证位置提取年份（第7-10位）
            // 即便不是真实身份证，只要是数字，就假定前6位是地区，接下里4位是年份
            const year = parseInt(idNum.substring(6, 10));
            const today = new Date();
            const currentYear = today.getFullYear();

            // 简单的合法性检查：年份应该在合理范围内（比如1900至今）
            if (year > 1900 && year <= currentYear) {
                 // 简单计算年龄：当前年份 - 出生年份
                 const age = currentYear - year;
                 if (age >= 0 && age <= 150) {
                    ageInput.value = age;
                 }
            }
        } catch (e) {
            console.log("自动计算年龄失败，请手动输入");
        }
    }
}

/**
 * 显示错误信息
 */
function showError(elementId, message) {
    const errorElement = document.getElementById(elementId);
    if (errorElement) {
        errorElement.textContent = message;
    }
}

/**
 * 清除错误信息
 */
function clearError(elementId) {
    const errorElement = document.getElementById(elementId);
    if (errorElement) {
        errorElement.textContent = '';
    }
}

/**
 * 显示提示信息
 */
function showAlert(message, type = 'error') {
    alertMessage.textContent = message;
    alertBox.className = 'alert ' + type;
    alertBox.style.display = 'flex';

    if (type !== 'success') {
        setTimeout(() => {
            alertBox.style.display = 'none';
        }, 5000);
    }
}

/**
 * 设置加载状态
 */
function setLoadingState(isLoading) {
    const btnText = registerBtn.querySelector('.btn-text');
    const btnLoading = registerBtn.querySelector('.btn-loading');

    if (isLoading) {
        btnText.style.display = 'none';
        btnLoading.style.display = 'inline';
        registerBtn.disabled = true;
    } else {
        btnText.style.display = 'inline';
        btnLoading.style.display = 'none';
        registerBtn.disabled = false;
    }
}

/**
 * 切换密码显示/隐藏
 */
function togglePasswordVisibility(inputId) {
    const input = document.getElementById(inputId);
    const toggleBtn = inputId === 'password' ? togglePasswordBtn : toggleConfirmPasswordBtn;
    const type = input.getAttribute('type');

    if (type === 'password') {
        input.setAttribute('type', 'text');
        toggleBtn.classList.remove('fa-eye');
        toggleBtn.classList.add('fa-eye-slash');
    } else {
        input.setAttribute('type', 'password');
        toggleBtn.classList.remove('fa-eye-slash');
        toggleBtn.classList.add('fa-eye');
    }
}